import {
  createOpenAPI,
  createWebsocket,
  IOpenAPI,
  IMessage,
  SessionEvents,
  AvailableIntentsEventsEnum
} from 'qq-guild-bot';
import { check } from './lib/bot';
import { init, dealMsg } from './lib/dealMsg';

import { green } from 'kolorist';
import { download } from './lib/tool';
import { EventEmitter } from 'ws';

declare global {
  var client: IOpenAPI;
  var bot: READY;
  var ws: EventEmitter;
}

interface READY {
  id: string;
  username: string;
  bot: boolean;
  status: number;
}

export default async function run(): Promise<void> {
  // 下载puppeteer
  await download();
  await check();
  // 创建 client

  const client = createOpenAPI(cfg);
  global.client = client;

  // 创建 websocket 连接
  const ws = createWebsocket(cfg);
  global.ws = ws;

  // 消息监听
  ws.on(SessionEvents.READY, (wsdata: { msg: { user: READY } }) => {
    // console.log('[READY] 事件接收 :', wsdata.msg.user);
    // console.log('机器人信息 :', wsdata.msg.user);
    // 保存机器人信息
    global.bot = wsdata.msg.user;
    init();
    console.info(green(`[登录] :机器人[${wsdata.msg.user.username}]已经准备就绪，可以开始使用`));
  });

  ws.on(SessionEvents.ERROR, (data: { msg: any }) => {
    console.log('[ERROR] 事件接收 :', data);
  });
  ws.on(AvailableIntentsEventsEnum.GUILDS, (data: { msg: any }) => {
    console.log('[GUILDS] 事件接收 :', data);
  });
  // 有人加入频道或退出频道
  ws.on(
    AvailableIntentsEventsEnum.GUILD_MEMBERS,
    (data: {
      eventType: string;
      msg: {
        guild_id: string;
        user: {
          avatar: string;
          bot: boolean;
          id: string;
          username: string;
        };
      };
    }) => {
      console.log('[GUILD_MEMBERS] 事件接收 :', data);
      if (data.eventType === 'GUILD_MEMBER_ADD') {
        console.info(
          green(
            `[加入] :成员[${data.msg.user.id}][${data.msg.user.username}]已经加入频道[${data.msg.guild_id}]`
          )
        );
      } else if (data.eventType === 'GUILD_MEMBER_REMOVE') {
        console.info(
          green(
            `[退出] :成员[${data.msg.user.id}][${data.msg.user.username}]已经退出频道[${data.msg.guild_id}]`
          )
        );
      } else {
        console.info(green(`[成员资料变更] :成员[${data.msg.user.id}][${data.msg.user.username}]`));
      }
    }
  );
  // 消息事件，仅 *私域* 机器人能够设置此 intents。
  ws.on(
    AvailableIntentsEventsEnum.GUILD_MESSAGES,
    async (e: { eventType: string; msg: IMessage }) => {
      // console.log('[GUILD_MESSAGES] 事件接收 :', e);

      if (e.eventType === 'MESSAGE_CREATE') {
        let { data } = await client.channelApi.channel(e.msg.channel_id);
        console.info(
          green(
            `[私域] [${e.msg.channel_id}] [${data.name}] [${e.msg.author.username}] [${
              e.msg.author.id
            }] : ${e.msg.content ? e.msg.content : ''} ${
              e.msg.attachments ? '\n' + JSON.stringify(e.msg.attachments, null, 2) : ''
            }`
          )
        );
      }
      // console.log(e);
      dealMsg(e);
    }
  );

  ws.on(AvailableIntentsEventsEnum.GUILD_MESSAGE_REACTIONS, (data: { msg: any }) => {
    console.log('[GUILD_MESSAGE_REACTIONS] 事件接收 :', data);
  });

  // 私聊消息
  ws.on(AvailableIntentsEventsEnum.DIRECT_MESSAGE, (data: { eventType: string; msg: IMessage }) => {
    // console.log('[DIRECT_MESSAGE] 事件接收 :', data);
    if (data.eventType === 'DIRECT_MESSAGE_CREATE') {
      console.info(
        green(
          `[私聊] [${data.msg.author.username}] [${data.msg.author.id}] : ${
            data.msg.content ? data.msg.content : ''
          }${data.msg.attachments ? '\n' + JSON.stringify(data.msg.attachments, null, 2) : ''}`
        )
      );
    }

    dealMsg(data);
  });

  ws.on(AvailableIntentsEventsEnum.INTERACTION, (data: { msg: any }) => {
    console.log('[INTERACTION] 事件接收 :', data);
  });

  ws.on(AvailableIntentsEventsEnum.MESSAGE_AUDIT, (data: { msg: any }) => {
    console.log('[MESSAGE_AUDIT] 事件接收 :', data);
  });

  ws.on(AvailableIntentsEventsEnum.FORUMS_EVENT, (data: { msg: any }) => {
    console.log('[FORUMS_EVENT] 事件接收 :', data);
  });

  ws.on(AvailableIntentsEventsEnum.AUDIO_ACTION, (data: { msg: any }) => {
    console.log('[AUDIO_ACTION] 事件接收 :', data);
  });
  // // 公域机器人
  // ws.on(AvailableIntentsEventsEnum.PUBLIC_GUILD_MESSAGES, async (e: { msg: IMessage }) => {
  //   // console.log('[PUBLIC_GUILD_MESSAGES] 事件接收 :', e);
  //   let { data } = await client.channelApi.channel(e.msg.channel_id);
  //   console.info(
  //     green(
  //       `[公域] [${e.msg.channel_id}] [${data.name}] [${e.msg.author.username}] [${e.msg.author.id}] : ${
  //         e.msg.content ? e.msg.content : ''
  //       } ${e.msg.attachments ? '\n' + JSON.stringify(e.msg.attachments, null, 2) : ''}`
  //     )
  //   );
  // });
}

run();
